<template>
  <div class="chat-container">
    <div class="chat-history" ref="chatHistoryRef">
      <div v-for="(msg, index) in chatHistory" :key="index" class="chat-message" :class="{'user-message': msg.role === 'user', 'bot-message': msg.role === 'bot'}">
        <v-md-preview class="message-content" :text="msg.content"></v-md-preview>
      </div>
    </div>
    <el-form ref="formRef" :model="formData" :rules="rules" size="default" class="chat-input-form">
      <el-form-item prop="msgInput" class="form-input" :show-message="false">
        <el-input class="input" v-model="formData.msgInput" type="textarea" placeholder="请输入内容"
                  :autosize="{minRows: 1, maxRows: 5}" resize="none"
                  @keydown.enter.exact.prevent="handleEnter"
                  @keydown.enter.shift.exact="handleShiftEnter"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup name="Chat">
/**
 * v-md-editor组件注册
 */
import VMdPreview from '@kangc/v-md-editor/lib/preview';
import '@kangc/v-md-editor/lib/style/preview.css';
import githubTheme from '@kangc/v-md-editor/lib/theme/github.js';
import '@kangc/v-md-editor/lib/theme/style/github.css';
import hljs from 'highlight.js';
import {getToken} from "@/utils/auth.js";
VMdPreview.use(githubTheme, {
  Hljs: hljs,
});
import { ref, reactive, toRefs, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {sendMessage} from "@/api/chat/chat.js";
import axios from 'axios'
import useUserStore from "@/store/modules/user.js"; // 引入axios用于发送HTTP请求

const userStore = useUserStore()
const formRef = ref()
const chatHistoryRef = ref()
const data = reactive({
  formData: {
    msgInput: '',
  },
  rules: {
    msgInput: [{
      required: true,
      message: '请输入内容',
      trigger: 'blur'
    }],
  },
  chatHistory: [] // 用于存储聊天记录
})

const { formData, rules, chatHistory } = toRefs(data)

/**
 * @name: 表单提交
 * @description: 表单提交方法
 * @return {*}
 */
async function submitForm() {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      const userInput = formData.value.msgInput;
      const userId = userStore.id;
      const userMessage = { role: 'user', content: userInput }
      chatHistory.value.push(userMessage) // 添加用户消息到聊天记录
      formData.value.msgInput = '' // 清空输入框
      scrollToBottom()
      sendMessage(userId, userInput).then(response => {
        if (response.code === 200) {
          const botMessage = { role: 'bot', content: response.msg }
          chatHistory.value.push(botMessage) // 添加后端回复到聊天记录
          scrollToBottom()
        } else {
          ElMessage.error('接收消息失败，请重试')
        }
      });
    } catch (error) {
      ElMessage.error('发送消息失败，请重试')
    }
  })
}

/**
 * @name: 表单重置
 * @description: 表单重置方法
 * @return {*}
 */
function resetForm() {
  formRef.value.resetFields()
}

/**
 * @name: 滚动到底部
 * @description: 滚动聊天记录到底部
 * @return {*}
 */
function scrollToBottom() {
  nextTick(() => {
    chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight
  })
}

/**
 * @name: 处理回车键
 * @description: 处理回车键发送消息
 * @return {*}
 */
function handleEnter() {
  submitForm()
}

/**
 * @name: 处理Shift+Enter键
 * @description: 处理Shift+Enter键换行
 * @return {*}
 */
function handleShiftEnter(event) {
  // event.target.value += '\n'
  formData.value.msgInput = event.target.value
}

onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
/**
删除输入框内置边框
 */
.form-input :deep(.el-textarea__inner) {
  border: none;
  box-shadow: none;
  padding: 0;
}
</style>
<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 84px);
  padding: 20px;
  box-sizing: border-box;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 20px;
  border-radius: 10px;
  --color: #E1E1E1;
  background-color: #F3F3F3;
  background-image: linear-gradient(0deg, transparent 24%, var(--color) 25%, var(--color) 26%, transparent 27%,transparent 74%, var(--color) 75%, var(--color) 76%, transparent 77%,transparent),
  linear-gradient(90deg, transparent 24%, var(--color) 25%, var(--color) 26%, transparent 27%,transparent 74%, var(--color) 75%, var(--color) 76%, transparent 77%,transparent);
  background-size: 55px 55px;
}

.chat-message {
  margin: 10px 0;
}

.user-message {
  text-align: right;
}

.bot-message {
  text-align: left;
}

.message-content {
  display: inline-block;
  padding: 8px 12px;
  border-style: solid;
  border-radius: 15px;
  background-color: #f0f0f0;
  max-width: 70%;
  word-wrap: break-word;
}

.user-message .message-content {
  background-color: #007bff;
  color: white;
}

.chat-input-form {
  display: flex;
  flex-direction: row;
}

.form-input {
  margin-right: 10px;
  width: 90%;
}

.form-input .el-input--medium .el-input__inner {
  border-top: none !important;
  border-left: none !important;
  border-right: none !important;
  border-radius: 0;
}

.input {
  width: 100%;
  height: 45px;
  padding: 12px;
  border-radius: 12px;
  border: 1.5px solid lightgrey;
  outline: none;
  transition: all 0.3s cubic-bezier(0.19, 1, 0.22, 1);
  box-shadow: 0px 0px 20px -18px;
}

.input:hover {
  border: 2px solid lightgrey;
  box-shadow: 0px 0px 20px -17px;
}

.input:focus {
  border: 2px solid grey;
}
</style>
